import Vue from 'vue'
import store from '@/store'
import DataDict from '@/utils/dict'
import { getDicts as getDicts } from '@/api/system/dict/data'
import Formatter from "./formatter";
let NO_CACHE = ['_baseClassAWarehouse','_baseClassBWarehouse','_baseClassBWarehouseId','_baseShop','_baseSupplierSelf'];
let CACHE_PROM = {};

function install() {
  Vue.use(DataDict, {
    metas: {
      '*': {
        labelField: 'dictLabel',
        valueField: 'dictValue',
        request(dictMeta,refresh) {
          let type = dictMeta.type;
          if(!refresh && NO_CACHE.indexOf(type)==-1){
            const storeDict = _.find(store.getters.dict, {key:type});
            if (storeDict) {
              return new Promise(resolve =>resolve(storeDict.value))
            }
          }
          // 加载
          if(CACHE_PROM[type]){
            //
          }else if(/^\_/.test(type)) {// _开头的type：走这个自定义过程
            CACHE_PROM[type] = Formatter.init(type).then((data)=>({data}));
          }else{
            CACHE_PROM[type] = getDicts(type);
          }
          //
          return CACHE_PROM[type].then((res)=>{
            store.dispatch('dict/setDict', { key: dictMeta.type, value: res.data })
            return res.data;
          }).finally(()=>{
            delete CACHE_PROM[type];
          })
        },
      },
    },
  })
}

export default {
  install,
}
